package com.sun.servlet;

import com.alibaba.fastjson.JSON;
import com.sun.dao.CategoryDao;
import com.sun.domain.Category;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author SunRui
 * @description category servlet
 * @date 2024/7/4 21:08
 */
@WebServlet(urlPatterns = "/CategoryServlet.action")
public class CategoryServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(ReaderServlet.class);
    InputStream resource = Resources.getResourceAsStream("mybatisConfig.xml");
    //获取session工厂对象
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);

    public CategoryServlet() throws IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取session会话对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        CategoryDao categoryDao = sqlSession.getMapper(CategoryDao.class);
        String opr = req.getParameter("opr");
        String jsonString = null;
        String str = null;
        switch (opr){
            case "homeUlLoad":
                //列表数据加载
                List<Category> categoryList = categoryDao.getList();
                logger.debug("列表数据:"+categoryList.toString());
                sqlSession.close();
                jsonString = JSON.toJSONString(categoryList);
                resp.getWriter().write(jsonString);
                break;
            case "categoryName":
                //根据id获取类型名称
                int id = Integer.parseInt(req.getParameter("categoryId"));
                String name = (String) categoryDao.getName(id);
                sqlSession.close();
                jsonString = JSON.toJSONString(name);
                resp.getWriter().write(jsonString);
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

}
